﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Admin/AdminSite.Master" AutoEventWireup="true"
    CodeBehind="ProductItem.aspx.cs" Inherits="phudieuhungthinh.Admin.ProductItem" %>

<%@ Register Src="~/Controls/FileBrowser.ascx" TagName="FileBrowser" TagPrefix="uc" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link href="/Styles/control-style.css" rel="stylesheet" type="text/css" />
    <link href="/third-party/jquery-ui-1.10.3/themes/base/minified/jquery-ui.min.css"
        rel="stylesheet" type="text/css" />
    <style type="text/css">
        .input
        {
            margin: 0px 0 10px 0;
        }
        label
        {
            width: 100px;
            display: block;
        }
        #upload-button
        {
            float: left;
            margin-top: 20px;
        }
        #image-upload
        {
            padding-top: 20px;
            height: 200px;
        }
        .btn-submit
        {
            background-color: #ccc;
            color: black;
            font-family: 'Oswald';
            font-size: 20px;
            text-decoration: none;
            cursor: pointer;
            border: none;
        }
        #display-image
        {
            height: 200px;
            border: solid 1px blue;
            margin-top: 20px;
            float: left;
            width: 641px;
        }
        #product-left
        {
            height: 500px;
            width: 300px;
            float: left;
        }
        .error-message
        {
            color: Red;
            height: 20px;
            width: 200px;
        }
        .error-message
        {
            color: Blue;
        }
    </style>
    <link href="/third-party/tiny_mce/themes/advanced/skins/default/ui.css" type="text/css" />
    <link href="/third-party/tiny_mce/plugins/inlinepopups/skins/clearlooks2/window.css"
        rel="Stylesheet" type="text/css" />
    <link href="/Scripts/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/uploadify/jquery.uploadify-3.1.js" type="text/javascript"></script>
    <script src="/Scripts/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="/third-party/tiny_mce/jquery.tinymce.js"></script>
    <script type="text/javascript" src="/third-party/tiny_mce/loadTinyMce.js"></script>
    <script type="text/javascript" src="/Scripts/vm/handler.js"></script>
    <script type="text/javascript" src="/third-party/jquery-validate/jquery.validate.js"></script>
    <script type="text/javascript" src="/Scripts/knockout.validation.js"></script>
    
    <script type="text/javascript">
        $(function () {
            loadTinyMce();
        });

        //or as a Number prototype method:
        Number.prototype.padLeft = function(n, str) {
            return Array(n - String(this).length + 1).join(str || '0') + this;
        };

        function acceptDialog() {
            var file;
            $('#file-explorer input[type=checkbox]:checked').each(function () {
                file = $(this).closest('div').next().prop('title');
                return;
            });
            $('#imgProduct').attr('src', '/images/products/thumb/' + file);
            $("#dialog-upload").dialog("close");
        }

        $(document).ready(function () {
            
            $('.button.upload a').click(function () {
                setupUpload('#file-explorer', 'products');
                $("#dialog-upload").dialog("open");
            });
            ko.extenders.required = function (target, overrideMessage) {
                //add some sub-observables to our observable
                target.hasError = ko.observable();
                target.validationMessage = ko.observable();

                //define a function to do validation
                function validate(newValue) {
                    target.hasError(newValue ? false : true);
                    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
                }
                //initial validation
                validate(target());
                //validate whenever the value changes
                target.subscribe(validate);
                //return the original observable
                return target;
            };
            function productVM() {
                var id = decodeURIComponent($.urlParam('id'));
                var self = this;
                self.name_keyup = function() {
                    if (self.name().length > 300) {
                        $('.error-message').remove();
                        $('#p-name').append("<span class='error-message'>Max length is 300 characters.</span>");
                    } else {
                        $('.error-message').remove();
                    }
                };
                if (id != 'null') {
                    $.ajax({
                        type: "POST",
                        url: location.pathname + "/GetProduct",
                        contentType: "application/json",
                        data: JSON.stringify({ id: id }),
                        dataType: "json",
                        async: false,
                        success: function (data) {
                            self.name = ko.observable(data.d.Name).extend({ required: "*" });
                            self.price = ko.observable(data.d.Price);
                            self.description = ko.observable(data.d.Description);
                            $('#imgProduct').attr('src', '/Images/products/thumb/' + data.d.ImageUrl);
                            if (self.name().length > 300) {
                                $('.error-message').remove();
                                $('#p-name').append("<span class='error-message'>Max length is 300 characters.</span>");
                            }
                            else {
                                $('.error-message').remove();
                            }
                        },
                        error: function () {
                            alert("Fail");
                        }
                    });

                    $.ajax({
                        type: "POST",
                        url: location.pathname + "/GetCategoryMenu",
                        contentType: "application/json",
                        dataType: "json",
                        data: JSON.stringify({ productId: id }),
                        async: false,
                        success: function (data) {
                            self.parentcategories = data.d.MenuList;
                        },
                        error: function () {
                            alert("Fail");
                        }
                    });
                }
                else {
                    self.name = ko.observable().extend({ required: "*" });
                    self.price = ko.observable();
                    self.description = ko.observable();
                    id = 0;

                    var cateid = decodeURIComponent($.urlParam('cateid'));
                    $.ajax({
                        type: "POST",
                        url: location.pathname + "/GetCategories",
                        contentType: "application/json",
                        dataType: "json",
                        data: JSON.stringify({ cateId: cateid }),
                        async: false,
                        success: function (data) {
                            self.parentcategories = data.d.MenuList;
                        },
                        error: function () {
                            alert("Fail");
                        }
                    });
                }
                self.errors = ko.validation.group(self);
                self.save = function() {
                    //Send this model to server
                    if (self.name().length > 300 || self.name() == '') {
                        return;
                    }
                    var categories = [];
                    $("#product-left input[type='checkbox']").each(function() {
                        if ($(this).is(':checked')) {
                            categories.push($(this).val());
                        }
                    });
                    var productModel = {
                        ID: id,
                        Name: self.name(),
                        Price: self.price(),
                        Description: $('#txtaDescription').tinymce().getContent(),
                        ImageUrl: $('#imgProduct').prop('src')
                    };
                    $.ajax({
                        type: "POST",
                        url: location.pathname + "/SaveProduct",
                        data: JSON.stringify({ productModel: productModel, arr: categories }),
                        contentType: "application/json",
                        success: function() {
                            if (id > 0) {
                                window.location.href = 'ProductDirectory.aspx';
                            } else {
                                $('.error-message').remove();
                                $('#s-message').append("<span class='error-message'>Lưu thành công.</span>");
                                // increase product name
                                var length1 = self.name().length;
                                var name = self.name().substring(0, length1 - 3);
                                var endStr = self.name().substring(length1 - 3, length1);
                                var i = parseInt(endStr, 10);

                                i++;
                                self.name(name + i.padLeft(3));

                                //Auto hide after 4 seconds.
                                $('.error-message').delay(3000).fadeOut('slow');
                            }
                        },
                        error: function() {
                            alert("Lưu thất bại");
                        }
                    });
                };
            }
            ko.applyBindings(new productVM());
        });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div id="product-body">
        <div id="product-left">
            <ul data-bind="template:{name: 'parentmenu', foreach: parentcategories, as: 'parent'}">
            </ul>
            <script type="text/html" id="parentmenu">
            <li>
                <input class = "checkbox" type="checkbox" data-bind ="attr: { value: ID, name: ID }, checked: Checked"><strong data-bind="text: Name" style="color:blue;"></strong>
                <ul data-bind="template: { name: 'submenu', foreach: SubMenus, as: 'sub' }"></ul>
            </li>
            </script>
            <script type="text/html" id="submenu">
            <li>
                <input type="checkbox" data-bind ="attr: { value: ID, name: ID }, checked: Checked"><span data-bind="text: Name"></span>                  
            </li>
            </script>
        </div>
        <div id="product-right">
            <fieldset>
                <legend>Sản phẩm</legend>
                <div class="input">
                    <label>
                        Tên sản phẩm :</label>
                    <p id="p-name" data-bind="css: { error: name.hasError }">
                        <input id="txtName" style="width: 300px" data-bind="value: name, valueUpdate: 'afterkeydown', event:{keyup: name_keyup}"
                            type="text" />
                        <span data-bind='visible: name.hasError, text: name.validationMessage'></span>
                    </p>
                </div>
                <div class="input">
                    <label for="lblPrice">
                        Giá :</label>
                    <p data-bind="css: { error: price.hasError }">
                        <input style="width: 300px" data-bind="value: price, valueUpdate: 'afterkeydown'"
                            type="text" />
                        <span id="span-message" data-bind='visible: price.hasError, text: price.validationMessage'>
                        </span>
                    </p>
                </div>
                <div class="input">
                    <label>
                        Mô tả (Description) :</label>
                    <textarea id="txtaDescription" style="height: 200px; width: 500px" class="tinymce"
                        rows="10" cols="2" data-bind="value: description"></textarea>
                </div>
                <div id="image-upload">
                    <label>
                        Hình ảnh (Photo) :</label>
                    <img id="imgProduct" src="" height="150px" width="250px" style="float: left" alt="" />
                    <%--<div id="upload-button">
                        <input class="joint" type='file' id="imgInp" />
                    </div>--%>
                    <div class="button upload">
                        <a href="javascript:void(0)">Up ảnh</a>
                    </div>
                </div>
                <div class="button save">
                    <a data-bind="click: save" href="javascript:void(0)">Lưu</a>
                </div>
                <span id="s-message"></span>
            </fieldset>
        </div>
    </div>
    <uc:FileBrowser ID="fileBrowser" runat="server" />
</asp:Content>
